<template>
    <div class="taskedit">
        <el-form ref="ruleFormRef" style="max-width: 80%" :model="form" :rules="rules" label-width="15%">
            <el-form-item label="年级：" prop="gradeLevel">
                <el-select v-model="form.gradeLevel" placeholder="年级" size="large" style="width: 240px;margin:0 10px;"
                    filterable clearable>
                    <el-option v-for="item in slevel" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="标题：" prop="title">
                <el-input v-model="form.title" style="width: 80%" placeholder="请输入标题" size="large" />
            </el-form-item>
            <el-form-item label="试卷:" prop="paperItems">
                <el-table :data="form.paperItems" border style="width: 100%">
                    <el-table-column prop="nam" label="学科" />
                    <el-table-column prop="name" label="名称" />
                    <el-table-column prop="createTime" label="创建时间" />
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button type="danger" @click="dele(scope.$index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                <el-button type="success" @click="addPaper">添加试卷</el-button>
            </el-form-item>
        </el-form>
    </div>

    <el-dialog v-model="dialogFormVisible" width="50%">
        <el-form :model="form">
            <div style="display: flex;align-items: center;">
                <h5>学科:</h5>
                <el-select v-model="data.subjectId" placeholder="年级" style="width: 240px;margin:0 10px;" filterable
                    clearable>
                    <el-option label="请选择" value="" />
                    <el-option v-for="item in subjectName" :key="item.id" :label="item.sname" :value="item.id" />
                </el-select>
                <el-button type="primary" @click="getList">查询</el-button>
            </div>
            <el-table :data="list" border style="width: 100%" :row-key="getRowKey"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40" />
                <el-table-column prop="id" label="Id" width="55" />
                <el-table-column prop="nam" label="学科" width="150" />
                <el-table-column prop="name" label="名称" width="85" />
                <el-table-column prop="createTime" label="创建时间" />
            </el-table>
            <div style="display: flex; align-items: center;height: 60px;">
                <span>共{{ total }}条</span>
                <div style="margin: 0 20px;">
                    <el-select v-model="data.pageSize" placeholder="Select" size="small" style="width: 100px"
                        @change="handleSizeChange">
                        <el-option v-for="item in psize" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </div>
                <el-pagination background layout="prev, pager, next" :total="total"
                    @current-change="handleCurrentChange" :current-page="data.pageIndex"
                    :page-sizes="[5, 10, 20, 30, 50]" :page-size="data.pageSize" />
                <div style="display: flex;width: 150px;justify-content: center;align-items: center;">
                    <span
                        style="display: flex;width: 60px;justify-content: center;align-items: center;">前往</span><el-input
                        v-model.lazy="data.pageIndex" class="center-input" style="width: 50px;" /><span
                        style="margin-left: 15px;">页</span>
                </div>
            </div>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="getSelectedData">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router';
import { search, subject, getpaper, add } from "@/api/task"
const route = useRoute();
const router = useRouter()
const form = ref({
    gradeLevel: '',
    id: '',
    title: "",
    paperItems: []
})
const data = ref({
    level: '',
    pageIndex: 1,
    pageSize: 5,
    paperType: 6,
    subjectId: ''
})
const list = ref<any>([])
const dialogFormVisible = ref(false)
var name = <any>[{}]
subject().then(res => {
    var sub = res.data.response.map((i: any) => {
        const sname = i ? `${i.name}(${i.levelName})` : '未知学科'
        return { ...i, sname }
    })
    name = sub
    console.log(name);
})
function getList() {
    getpaper(data.value).then(res => {
        if (res.status === 200) {
            console.log(res);
            
            const resp = res.data.response.list.map((i: any) => {
                const sn = name.find((l: any) => l.id == i.subjectId)
                const nam = sn?.sname
                return { ...i, nam }
            })
            total.value = res.data.response.total
            list.value = resp
            console.log(resp);
            
        }
    })
}
function dele(row: any) {
    console.log(row);
    form.value.paperItems.splice(row, 1)
}
function addPaper() {
    data.value.level = form.value.gradeLevel
    dialogFormVisible.value = true
    getList()
}
let total = ref(0)
const psize = ref([
    { label: '共5条', value: 5 },
    { label: '共10条', value: 10 },
    { label: '共20条', value: 20 },
    { label: '共30条', value: 30 },
    { label: '共40条', value: 40 },
    { label: '共50条', value: 50 }
])
const handleCurrentChange = (page: number) => {
    data.value.pageIndex = page
    getList()
}
// 每页条数变化时触发
const handleSizeChange = (size: number) => {
    data.value.pageSize = size
    data.value.pageIndex = 1 // 重置为第一页
    getList()
}
watch(() => data.value.pageIndex, (newValue, oldValue) => {
    if (!newValue) {
        data.value.pageIndex = oldValue
    } else {
        data.value.pageIndex = newValue;
        getList()
    }
});
const selectedRows = ref<any>([])
// 设置行键（必须，用于唯一标识行）
const getRowKey = (row: { id: number }) => row.id
// 监听选择变化
const handleSelectionChange = (rows: any) => {
    selectedRows.value = rows
    console.log(rows);
}

const getSelectedData = () => {
    selectedRows.value.forEach((item: any) => {
        form.value.paperItems.push(item);
    })
    dialogFormVisible.value = false
}

let subjectName = computed<any>(() => {
    if (!form.value.gradeLevel) return []
    return name.filter((subject: any) => subject.level === form.value.gradeLevel)
})

watch(() => form.value.gradeLevel, () => {
    data.value.level = ''
})
const id: any = route.query.id
if (id && id.length > 0) {
    search(id).then(res => {
        console.log(res);
        if (res.status === 200) {
            const dormdata = res.data.response.paperItems.map((i: any) => {
                const na = name.find((l: any) => l.level = i.id)
                const nam = na?.sname
                return { ...i, nam }
            })
            res.data.response.paperItems = dormdata
            form.value = res.data.response
            console.log(res.data.response);

        }
    })
}

const ruleFormRef = ref<FormInstance>()
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            add(form.value).then(res => {
                if (res.status === 200) {
                    ElMessage.success('编辑成功')
                    setTimeout(() => {
                        router.push('list')
                    }, 1500)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
const rules = reactive<FormRules>({
    gradeLevel: [{ required: true, message: '请选择年级', trigger: 'blur' },],
    title: [{ required: true, message: '请填写标题', trigger: 'blur', },],
    paperItems: [{ required: true, message: '请选择试卷类', trigger: 'blur', },],
})
const slevel = [
    { label: '一年级', value: 1 },
    { label: '二年级', value: 2 },
    { label: '三年级', value: 3 },
    { label: '四年级', value: 4 },
    { label: '五年级', value: 5 },
    { label: '六年级', value: 6 },
    { label: '初一', value: 7 },
    { label: '初二', value: 8 },
    { label: '初三', value: 9 },
    { label: '高一', value: 10 },
    { label: '高二', value: 11 },
    { label: '高三', value: 12 },
]

</script>

<style scoped>
::v-deep .center-input .el-input__inner {
    text-align: center;
}
</style>